from django.contrib.auth.models import AbstractUser
from django.db import models
from django.db.models.signals import post_save
from api.utils.db_functions import make_uuid


class User(AbstractUser):
    roles = []

    id = models.UUIDField(
        primary_key=True, help_text="ID of user", default=make_uuid, editable=True
    )
    username = models.CharField(default="", max_length=128, unique=True)
    mobile = models.CharField(max_length=11, unique=True, verbose_name="手机号")

    class Meta:
        db_table = "tb_users"
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username


class Profile(models.Model):
    user = models.OneToOneField(User, related_name="profile", on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return "%s's profile" % self.user

    class Meta:
        ordering = ("-created_at",)


def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


class ShopAddress(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="addreses")
    province = models.CharField(help_text="省", default="", max_length=64)
    city = models.CharField(help_text="市", default="", max_length=64)
    area = models.CharField(help_text="区", default="", max_length=64)
    detailed = models.CharField(help_text="详细地址", default="", max_length=256)
    default = models.BooleanField(help_text="是否默认", default=False)
    deleted = models.BooleanField(help_text="是否删除", default=False)


class Address(models.Model):
    parent = models.IntegerField(help_text="父级地址ID", default=0)
    number = models.IntegerField(help_text="地址ID", default=0)
    address = models.CharField(help_text="地址名称", max_length=256, default="")


post_save.connect(create_user_profile, sender=User)
